class Demand < ActiveRecord::Base

  # scope
  default_scope -> { order("created_at DESC") }

  # Associations
  belongs_to :creator, class_name: "User", foreign_key: "creator_id"
  has_many :messages
  has_many :images, -> { where image_type: IMAGE_TYPE["服务图片"] }, foreign_key: "owner"

  # default per_page value for kaminari
  paginates_per 6

  class << self
    def create_with_images(params)
      transaction do
        demand = create(title: params[:title],
                        description: params[:description],
                        status: DEMAND_TYPE["未完成"],
                        creator_id: params[:creator_id])

        User.update(params[:creator_id], location: params[:location],
                                         longitude: params[:longitude],
                                         latitude: params[:latitude])

        if params[:images].present?
          params[:images].each do |base_64_encoded_data|
            Image.create(base_64_encoded_data: base_64_encoded_data,
                        image_type: IMAGE_TYPE["服务图片"],
                        owner: demand.id)
          end
        end
      end
    end
  end
end